/**
 * 项目管理路由
 *
 * Created by snowingsea on 2020/02/06.
 */
const middleware = require('./../middleware');
const projectVersions = require('./../../models/project-versions');
const PhoenixError = require('./../../models/phoenix-error');

/**
  * 获取项目信息
  * @param req
  * @param res
  * @param next
  */
function getProjectVersionsNamesSet(req, res, next) {
  (async () => {
    const {
      projectName, userId,
    } = req.query;
    if (projectName === undefined) {
      throw new PhoenixError('invalid request', 'need projectName');
    }
    const names = await projectVersions.namesSet(projectName, userId, {
      lastProjectOnly: !userId,
      lastVersionOnly: !(userId && projectName),
    });
    res.json({ names });
  })()
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

function getStaticAnalyzeOverviewList(req, res, next) {
  (async () => {
    const {
      projectName,
      versionName,
      userId,
      q,
      sortBy,
      order,
    } = req.query;
    let {
      page,
      perPage,
    } = req.query;
    page = parseInt(page, 10) || 1;
    perPage = parseInt(perPage, 10) || 100;
    const { total, versions } = await projectVersions.getStaticAnalyzeOverviewList({
      page,
      pageSize: perPage,
      projectName,
      versionName,
      userId,
      q,
      sortBy,
      order,
      lastProjectOnly: !userId,
      lastVersionOnly: !(userId && projectName),
    });
    res.json({
      pagination: {
        total,
        page,
        perPage,
        sortBy,
        order,
      },
      versions,
    });
  })()
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
  * Export model definition object.
  */
module.exports = (app, prefix) => {
  const projectsNamesSetURL = `${prefix}/versions/names-set.json`;
  const staticAnalyzeOverviewList = `${prefix}/static-analyze/versions.json`;
  // 获取项目版本名称集合（去重）
  app.get(projectsNamesSetURL, middleware.user.requireTokenUnexpired);
  app.get(projectsNamesSetURL, middleware.user.requireAvailable);
  app.get(projectsNamesSetURL, middleware.user.requireTestManager);
  app.get(projectsNamesSetURL, getProjectVersionsNamesSet);

  app.get(staticAnalyzeOverviewList, middleware.user.requireTokenUnexpired);
  app.get(staticAnalyzeOverviewList, middleware.user.requireAvailable);
  app.get(staticAnalyzeOverviewList, middleware.user.requireTestManager);
  app.get(staticAnalyzeOverviewList, getStaticAnalyzeOverviewList);
};
